﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.XPath;

namespace Dx.Common.Common
{
    public class XmlHelper
    {
        private XDocument _document;

        /// <summary>
        /// 加载 XML 文件
        /// </summary>
        /// <param name="filePath"></param>
        public void Load(string filePath)
        {
            _document = XDocument.Load(filePath);
        }

        // 保存 XML 文件
        public void Save(string filePath)
        {
            _document.Save(filePath);
        }

        // 获取节点值
        public string GetNodeValue(string xpath)
        {
            var element = _document.XPathSelectElement(xpath);
            return element?.Value;
        }

        // 设置节点值
        public void SetNodeValue(string xpath, string value)
        {
            var element = _document.XPathSelectElement(xpath);
            if (element != null)
            {
                element.Value = value;
            }
        }

        // 获取属性值
        public string GetAttributeValue(string xpath, string attributeName)
        {
            var element = _document.XPathSelectElement(xpath);
            return element?.Attribute(attributeName)?.Value;
        }

        // 设置属性值
        public void SetAttributeValue(string xpath, string attributeName, string value)
        {
            var element = _document.XPathSelectElement(xpath);
            if (element != null)
            {
                element.SetAttributeValue(attributeName, value);
            }
        }

        // 添加新节点
        public void AddNode(string parentXpath, string newNode, string value)
        {
            var parentElement = _document.XPathSelectElement(parentXpath);
            if (parentElement != null)
            {
                parentElement.Add(new XElement(newNode, value));
            }
        }

        // 删除节点
        public void DeleteNode(string xpath)
        {
            var element = _document.XPathSelectElement(xpath);
            element?.Remove();
        }
    }
}
